import Vue 			from "vue";
import API from '../../api/api'
import Types from '../mutation-types'
/**
 * get请求
 * @param  {String} options.url   api地址
 * @param  {String} options.query query参数
 * @return {Promise}               Promise
 */
const _get = ({ url, query }) => {
  return Vue.http.get({
    url: API.apiUrl+url,
    method:'get'
  }).then((res) => {
    if (res.status >= 200 && res.status < 300) {
      return res.data;
    }
    return Promise.reject(new Error(res.status));
  });
};
/**
 * post请求
 * @param  {String} url    api地址
 * @param  {Object} params 包含post内容的object
 * @return {Promise}        Promise
 */
const _post = (url, params) => {
  return _get({url,params})
  return Vue.http.post({
		url: API.apiUrl+url,
		method:'post'
	}).then((res) => {
    if (res.status >= 200 && res.status < 300) {
      return res.data;
    }
    return Promise.reject(new Error(res.status));
  });
};

export const doLogin=({ dispatch }, {password,account})=>{
  const url = 'login.json';
  const params = { password, account };
  return _post(url, params)
  .then((json) => {
    if (json.success) {
      dispatch(Types.CHECK_TOKEN_SUCCESS,json);
      return json.loginname;
    }
    return Promise.reject(new Error('checkToken failure'));
  })
  .catch((error) => {
    dispatch('CHECK_TOKEN_FAILURE');
    return Promise.reject(error);
  });
}
